package com.zxy.rule;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.ExtendBalancer;
import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
//@Component
public class MyRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private NacosServiceManager nacosServiceManager;

    //JUC包
    private static AtomicInteger cout = new AtomicInteger(0);

    @Override
    @SneakyThrows
    public Server choose(Object key) {

        String group = this.nacosDiscoveryProperties.getGroup();
        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
        String name = loadBalancer.getName();
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        List<Instance> instances = null;
        instances = namingService.selectInstances(name, group, true);
        if (CollectionUtils.isEmpty(instances)) {
            log.warn("no instance in service {}", name);
            return null;
        }
        Instance maxInstance = instances.stream().max(Comparator.comparing(Instance::getWeight)).get();
        Instance minInstance = instances.stream().min(Comparator.comparing(Instance::getWeight)).get();
        int count2 = cout.incrementAndGet();
        int mod = count2 % 5;
        if (mod == 0) {
            log.debug("count={},mod={},使用min",count2, mod);
            return new NacosServer(minInstance);
        } else {
            log.debug("count={},mod={},使用max",count2, mod);
            return new NacosServer(maxInstance);
        }

    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

}